package net.flowas.genericcrud.service.chain;

import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.ResourceBundle;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.flowas.genericcrud.ResourceRegister;

public class I18nRegister implements ResourceRegister {
	private static final Logger LOG = LoggerFactory.getLogger(ResourceRegister.class);
	//i18n.properties
	private static final String I18N_BASE_FILE = "i18n";

	private Map<String, String> i18n = new HashMap<>();

	public I18nRegister() {
		ResourceBundle i18nMsg = ResourceBundle.getBundle(I18N_BASE_FILE);
		for (String key : i18nMsg.keySet()) {
			i18n.put(key, i18nMsg.getString(key));
		}
	}

	@Override
	public void addResource(URL url, ClassLoader classLoader) {
		Properties properties = new Properties();
		try {
			properties.load(url.openStream());
			Enumeration<Object> keys = properties.keys();
			while(keys.hasMoreElements()) {
				String key = (String) keys.nextElement();
				//如果已经包含键值对，覆盖旧值
				i18n.put(key, properties.getProperty(key));
			}
		} catch (IOException e) {
			LOG.error("failed to load i18n resource",e);
		}
	}

	@Override
	public void removeResource(URL url) {
		Properties properties = new Properties();
		try {
			properties.load(url.openStream());
			Enumeration<Object> keys = properties.keys();
			while(keys.hasMoreElements()) {
				String key = (String) keys.nextElement();
				i18n.remove(key);
			}
		} catch (IOException e) {
			LOG.error("failed to remove i18n resource",e);
		}
	}

	/**
	 * 获取国际化字符串键值对应的国际化数据值.
	 * @param key
	 * @return
	 */
	public String get(String key) {
		return i18n.get(key);
	}

	public Map<String, String> i18nToMap() {
		return i18n;
	}
}
